package com.wosai.teach.activity;

import java.io.File;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.HttpHandler.State;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.wosai.teach.R;
import com.wosai.teach.adapter.WhoUsedAdapter;
import com.wosai.teach.cst.C;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.DownloadInfo;
import com.wosai.teach.entity.ExpDateRel;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.entity.WhoUsed;
import com.wosai.teach.service.DownLoadFactory;
import com.wosai.teach.service.DownLoadService;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.BitmapHelp;
import com.wosai.teach.utils.ListViewUtils;
import com.wosai.teach.utils.NetWorkUtils;
import com.wosai.teach.utils.OtherUtils;
import com.wosai.teach.view.BannerView;

/**
 * @author : qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015-5-13 上午9:42:24
 * @desc :
 */
@ContentView(R.layout.activity_exp_dtl)
public class ExpDetailAction extends AppActivity {

	@ViewInject(R.id.exp_dtl_key)
	private TextView key;

	@ViewInject(R.id.exp_dtl_info)
	private TextView info;

	@ViewInject(R.id.exp_dtl_icon)
	private ImageView icon;

	@ViewInject(R.id.exp_dtl_who_used)
	private ListView whoUsed;

	@ViewInject(R.id.banner_view)
	private BannerView bannerView;

	@ViewInject(R.id.exp_dtl_name)
	private TextView name;

	@ViewInject(R.id.exp_dtl_ver)
	private TextView ver;

	@ViewInject(R.id.exp_dtl_bt_install)
	private Button btInstall;

	@ViewInject(R.id.exp_dtl_ll)
	private LinearLayout ll;

	@ViewInject(R.id.exp_dtl_ll2)
	private LinearLayout ll2;

	@ViewInject(R.id.exp_dtl_bt_open)
	private Button btOpen;

	@ViewInject(R.id.exp_dtl_bt_update)
	private Button btUpdate;

	@ViewInject(R.id.exp_dtl_bt_uninstall)
	private Button btUninstall;

	@ViewInject(R.id.exp_dtl_rl_bar)
	private RelativeLayout rlBar;

	@ViewInject(R.id.exp_dtl_bar)
	private ProgressBar bar;

	@ViewInject(R.id.exp_dtl_percent)
	private TextView percent;

	private Experiment exp;

	private BitmapUtils bitmapUtils;

	private PackageInfo packageInfo;

	private boolean info_status = false;

	private boolean hasCar = false;

	private DownLoadFactory factory;

	private DownloadInfo downloadInfo;

	private DownloadRequestCallBack callBack;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bitmapUtils = BitmapHelp.getBitmapUtils(this);
		Intent it = getIntent();
		String expId = it.getStringExtra("expId");
		exp = db.findFirst(Selector.from(Experiment.class).where("expId", "=",
				expId));
		setTopTitle(exp.getExpName());
		enableBack(true);
		factory = DownLoadService.getDownLoadManager(getApplicationContext());
		initView();
		loadSoftInfo();
	}

	public void initView() {
		this.packageInfo = AppUtil.getPackageInfo(exp.getApkPackageName());
		bitmapUtils.display(icon, exp.getIcon1());
		name.setText(exp.getExpName());
		key.setText("关键字:加载中");
		info.setText("描述：加载中");
		ver.setText("版本：" + AppUtil.getVersionName(packageInfo));
		rlBar.setVisibility(View.INVISIBLE);
		key.setText("关键字: " + exp.getKeywords());
		info.setText("" + exp.getDetailInfo());
		exeCar();

		if (callBack == null) {
			callBack = new DownloadRequestCallBack();
			factory.refreshCallBack(exp.getExpId() + "", callBack);
			refresh();
		}
		int version = AppUtil.getVersionCode(packageInfo);
		if (version > 0) {
			// 已安装
			ll2.setVisibility(View.VISIBLE);
			ll.setVisibility(View.GONE);
			if (version < exp.getApkVer()) {
				downloadInfo = factory.getDownloadInfo(exp.getExpId() + "");
				if (downloadInfo == null) {
					// 删除已下载的包,再更新
					delApk();
				}
				refreshView(btUpdate);
			} else {
				btUpdate.setEnabled(false);
			}
		} else {
			ll.setVisibility(View.VISIBLE);
			ll2.setVisibility(View.GONE);
			refreshView(btInstall);
		}
	}

	@OnClick(R.id.exp_dtl_bt_open)
	public void openSoft(View v) {
		// boolean toLogin = AppUtil.toLogin(this);
		refreshDateRel();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		ComponentName cn = new ComponentName(exp.getApkPackageName(),
				exp.getApkClassName());
		intent.setComponent(cn);
		intent.putExtra("userId", 16);
		startActivity(intent);
	}

	/**
	 * 刷新打开记录
	 */
	private void refreshDateRel() {
		ExpDateRel rel = db.findFirst(Selector.from(ExpDateRel.class).where(
				"expId", "=", exp.getExpId()));
		if (rel == null) {
			rel = new ExpDateRel();
			rel.setCreateDate(new Date().getTime());
			rel.setExpId(exp.getExpId() + "");
		}
		rel.setUpdateDate(new Date().getTime());
		db.save(rel);
	}

	@OnClick(R.id.exp_dtl_bt_uninstall)
	public void uninstallSoft(View v) {
		Uri packageURI = Uri.parse("package:" + exp.getApkPackageName()); // 包名
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivityForResult(uninstallIntent, C.REQUEST_CODE_UNINSTALL);
	}

	@OnClick({ R.id.exp_dtl_bt_install, R.id.exp_dtl_bt_update })
	public void installSoft(View v) {
		refreshDownLoadInfo();
		HttpHandler.State state = downloadInfo.getState();
		switch (state) {
		case WAITING:
			checkNetWork(state);
			break;
		case STARTED:
		case LOADING:
			factory.stopDownload(exp.getExpId() + "");
			break;
		case CANCELLED:
		case FAILURE:
			checkNetWork(state);
			break;
		case SUCCESS:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			String savePath = downloadInfo.getFileSavePath();// apk路径
			if (OtherUtils.CheckNull(savePath)) {
				return;
			}
			intent.setDataAndType(Uri.fromFile(new File(savePath)),
					"application/vnd.android.package-archive");
			if (v.getId() == R.id.exp_dtl_bt_install) {
				startActivityForResult(intent, C.REQUEST_CODE_INSTALL);
			} else {
				startActivityForResult(intent, C.REQUEST_CODE_UPDATE);
			}
			break;
		default:
			break;
		}
		refreshView((TextView) v);
	}

	/**
	 * 根据网络类型操作
	 * 
	 * @param state
	 */
	public void checkNetWork(final State state) {
		int netType = NetWorkUtils.getNetworkType(this);
		if (netType == NetWorkUtils.NETTYPE_NO) {
			toastShow("亲，请连接网络先");
			return;
		}
		if (netType != NetWorkUtils.NETTYPE_WIFI) {
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setMessage("您当前未连接WIFI，是否确认下载安装")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (state == State.WAITING) {
										factory.addNewDownload(downloadInfo,
												callBack);
									} else if (state == State.CANCELLED
											|| state == State.FAILURE) {
										factory.resumeDownload(exp.getExpId()
												+ "", callBack);
									}
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 点击“返回”后的操作,这里不设置没有任何操作
								}
							}).show();
		} else {
			if (state == State.WAITING) {
				factory.addNewDownload(downloadInfo, callBack);
			} else if (state == State.CANCELLED || state == State.FAILURE) {
				factory.resumeDownload(exp.getExpId() + "", callBack);
			}
		}
	}

	@OnClick(R.id.exp_dtl_info)
	public void showInfo(View v) {
		if (info_status) { // 收拢
			info_status = false;
			info.setEllipsize(TextUtils.TruncateAt.END);
			info.setLines(3);
		} else { // 展开
			info_status = true;
			info.setEllipsize(null);
			info.setSingleLine(false);
		}
	}

	/**
	 * 刷新按钮
	 * 
	 * @param v
	 */
	private void refreshView(TextView v) {
		refreshDownLoadInfo();
		HttpHandler.State state = downloadInfo.getState();
		switch (state) {
		case WAITING:
			v.setText(AppUtil.getVersionCode(packageInfo) == 0 ? "下载" : "更新");
			break;
		case STARTED:
		case LOADING:
			v.setText("下载中");
			if (rlBar.getVisibility() == View.INVISIBLE) {
				rlBar.setVisibility(View.VISIBLE);
			}
			break;
		case CANCELLED:
			v.setText("暂停");
			if (rlBar.getVisibility() == View.INVISIBLE) {
				rlBar.setVisibility(View.VISIBLE);
			}
			break;
		case FAILURE:
			v.setText(AppUtil.getVersionCode(packageInfo) == 0 ? "下载" : "更新");
			break;
		case SUCCESS:
			if (rlBar.getVisibility() == View.VISIBLE) {
				rlBar.setVisibility(View.INVISIBLE);
			}
			v.setText("安装");
			break;
		default:
			break;
		}
	}

	private void loadSoftInfo() {
		String url = C.HTTP_URL_WHO_USED;
		url = url.replace("{expId}", exp.getExpId() + "");
		url = url.replace("{userId}", 0 + "");
		url = url.replace("{pageSize}", 10 + "");
		url = url.replace("{currentPage}", 1 + "");
		System.out.println(url);
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							List<WhoUsed> wuList = JSON.parseArray(result
									.getObject().toString(), WhoUsed.class);
							if (OtherUtils.CheckNull(wuList)) {
								return;
							}
							db.deleteAll(Selector.from(WhoUsed.class).where(
									"expId", "=", exp.getExpId()));
							db.saveAll(wuList);
							exeWhoUsed();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						exeWhoUsed();
					}
				});
	}

	private void exeWhoUsed() {
		List<WhoUsed> wuList = db.findAll(Selector.from(WhoUsed.class).where(
				"expId", "=", exp.getExpId()));
		if (OtherUtils.CheckNull(wuList)) {
			return;
		}
		this.whoUsed.setVisibility(View.VISIBLE);
		WhoUsedAdapter adapter = new WhoUsedAdapter(this, wuList);
		this.whoUsed.setAdapter(adapter);
		ListViewUtils.setListViewHeightBasedOnChildren(this.whoUsed);
	}

	/**
	 * 轮播，活动
	 * 
	 * @param expDtl
	 */
	private void exeCar() {
		if (hasCar) {
			return;
		}
		hasCar = !hasCar;
		String[] pic = { exp.getPicURL1(), exp.getPicURL2(), exp.getPicURL3(),
				exp.getPicURL4(), exp.getPicURL5() };
		bannerView.initAttribute(bitmapUtils);
		bannerView.addImages(pic);
	}

	private void refresh() {
		refreshDownLoadInfo();
		if (downloadInfo.getFileLength() > 0) {
			int result = (int) (downloadInfo.getProgress() * 100 / downloadInfo
					.getFileLength());
			bar.setProgress(result);
			percent.setText(result + "%");
		} else {
			bar.setProgress(0);
		}
		Button tt = null;
		int version = AppUtil.getVersionCode(packageInfo);
		if (version > 0) {
			tt = btUpdate;
		} else {
			tt = btInstall;
		}
		HttpHandler.State state = downloadInfo.getState();
		switch (state) {
		case WAITING:
			break;
		case STARTED:
			break;
		case LOADING:
			tt.setText("下载中");
			if (rlBar.getVisibility() == View.INVISIBLE) {
				rlBar.setVisibility(View.VISIBLE);
			}
			break;
		case CANCELLED:
			tt.setText("暂停");
			if (rlBar.getVisibility() == View.INVISIBLE) {
				rlBar.setVisibility(View.VISIBLE);
			}
			break;
		case SUCCESS:
			tt.setText("安装");// 下载完成
			if (rlBar.getVisibility() == View.VISIBLE) {
				rlBar.setVisibility(View.INVISIBLE);
			}
			break;
		case FAILURE:
			tt.setText("下载");// 重新下载
			break;
		}
	}

	private void refreshDownLoadInfo() {
		if (downloadInfo == null) {
			downloadInfo = factory.getDownloadInfo(exp.getExpId() + "");
		}
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		String savePath = sdcard + "/teach_platform/" + fileName;
		if (downloadInfo == null) {
			downloadInfo = new DownloadInfo();
			downloadInfo.setDownloadUrl(exp.getApkURL());
			downloadInfo.setAutoRename(false);
			downloadInfo.setAutoResume(true);
			downloadInfo.setFileName(fileName);
			downloadInfo.setFileSavePath(savePath);
			downloadInfo.setRelId(exp.getExpId() + "");
			downloadInfo.setState(State.WAITING);
		}
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			if (downloadInfo.getState() == State.FAILURE) {
				// 下载失败.删除后,再重新下载
				delApk();
			}
		} else {
			if (downloadInfo.getState() == State.SUCCESS) {
				// 下载成功,但是没有文件,文件被删除,重新下载
				downloadInfo.setState(State.WAITING);
			}
		}
	}

	private void delApk() {
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			return;
		}
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String savePath = sdcard + "/teach_platform/" + fileName;
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			apk.delete();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.REQUEST_CODE_UNINSTALL) {
			// 删除安装包
			delApk();
			initView();
		} else if (requestCode == C.REQUEST_CODE_INSTALL) {
			initView();
		} else if (requestCode == C.REQUEST_CODE_UPDATE) {
			initView();
		}
	}

	private class DownloadRequestCallBack extends RequestCallBack<File> {

		private void refreshListItem() {
			refresh();
		}

		@Override
		public void onStart() {
			refreshListItem();
		}

		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			refreshListItem();
		}

		@Override
		public void onSuccess(ResponseInfo<File> responseInfo) {
			refreshListItem();
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			refreshListItem();
		}

		@Override
		public void onCancelled() {
			refreshListItem();
		}
	}
}
